"""
种子保存模块 - 处理种子的保存和文件操作
"""

import os
import json
import shutil
from datetime import datetime


#TODO 不要json的种子数据统计，种子目录下面只有种子

class SeedSaver:
    def __init__(self, base_output_dir="ai_seeds"):
        self.base_output_dir = base_output_dir

    def save_seeds(self, seeds_text, program_path, program_name):
        """保存种子文件并返回统计信息"""

        # 创建程序特定的输出目录
        safe_name = self._make_safe_filename(program_name)
        output_dir = os.path.join(self.base_output_dir, safe_name)

        # 清理已存在的目录（如果存在）
        self._clean_existing_directory(output_dir)

        # 创建新目录
        os.makedirs(output_dir, exist_ok=True)

        # 清理和分割种子文本
        seeds = self._clean_seeds_text(seeds_text)

        # 保存每个种子为单独文件
        valid_seeds = []
        for i, seed in enumerate(seeds):
            if 0 < len(seed) <= 10000:  # 合理长度限制
                filename = f"seed_{i:06d}"
                filepath = os.path.join(output_dir, filename)

                try:
                    with open(filepath, 'w', encoding='utf-8') as f:
                        f.write(seed)
                    valid_seeds.append({
                        'filename': filename,
                        'content': seed,
                        'length': len(seed)
                    })
                except Exception as e:
                    print(f" 保存种子 {filename} 时出错: {e}")

        seed_count = len(valid_seeds)

        # 保存生成报告
        self._save_generation_report(output_dir, program_path, seed_count, valid_seeds)

        return {
            'output_dir': output_dir,
            'seed_count': seed_count,
            'seeds': valid_seeds
        }

    def _clean_existing_directory(self, directory_path):
        """清理已存在的目录"""
        if os.path.exists(directory_path):
            print(f" 清理已存在的目录: {directory_path}")
            try:
                # 删除目录及其所有内容
                shutil.rmtree(directory_path)
                print(f"✅ 已删除旧目录: {directory_path}")
            except Exception as e:
                print(f" 清理目录失败 {directory_path}: {e}")
                # 如果删除失败，尝试删除目录内的文件但保留目录
                self._clean_directory_files(directory_path)

    def _clean_directory_files(self, directory_path):
        """清理目录内的所有文件但保留目录"""
        try:
            for filename in os.listdir(directory_path):
                file_path = os.path.join(directory_path, filename)
                if os.path.isfile(file_path):
                    os.remove(file_path)
                    print(f"  已删除文件: {filename}")
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
                    print(f"  已删除子目录: {filename}")
            print(f"✅ 已清理目录内容: {directory_path}")
        except Exception as e:
            print(f"❌ 清理目录内容失败 {directory_path}: {e}")

    def _make_safe_filename(self, filename):
        """创建安全的文件名"""
        safe_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."
        safe_name = ''.join(c for c in filename if c in safe_chars)
        # 如果文件名过长，截断
        if len(safe_name) > 100:
            name, ext = os.path.splitext(safe_name)
            safe_name = name[:100-len(ext)] + ext
        return safe_name

    def _clean_seeds_text(self, seeds_text):
        """清理种子文本"""
        seeds = []
        for line in seeds_text.split('\n'):
            line = line.strip()
            # 跳过空行和明显的注释/编号行
            if line and not any(indicator in line for indicator in
                                ['##', '类别', '正常输入', '边界测试', '格式错误',
                                 '攻击载荷', '随机变异', '===', '---', '```']):
                # 移除可能的编号前缀
                if len(line) > 2 and line[0].isdigit() and (line[1] == '.' or line[1] == '、'):
                    line = line[2:].strip()
                # 移除代码块标记
                if line.startswith('```') and line.endswith('```'):
                    continue
                seeds.append(line)
        return seeds

    def _save_generation_report(self, output_dir, program_path, seed_count, seeds):
        """保存生成报告"""
        report = {
            'program': program_path,
            'seed_count': seed_count,
            'timestamp': datetime.now().isoformat(),
            'output_dir': os.path.abspath(output_dir),
            'seeds_summary': [
                {'filename': s['filename'], 'length': s['length']}
                for s in seeds
            ]
        }

        report_file = os.path.join(output_dir, 'generation_report.json')
        try:
            with open(report_file, 'w', encoding='utf-8') as f:
                json.dump(report, f, indent=2, ensure_ascii=False)
            print(f" 已保存生成报告: {report_file}")
        except Exception as e:
            print(f" 保存报告失败: {e}")

    def backup_existing_seeds(self, backup_dir="ai_seeds_backup"):
        """备份已存在的种子目录（可选功能）"""
        if not os.path.exists(self.base_output_dir):
            return

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_path = os.path.join(backup_dir, f"seeds_backup_{timestamp}")

        try:
            if os.path.exists(self.base_output_dir):
                shutil.copytree(self.base_output_dir, backup_path)
                print(f" 已备份种子到: {backup_path}")
        except Exception as e:
            print(f" 备份失败: {e}")